package org.lemon.cla.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.lemon.cla.pojo.Club;
import org.lemon.cla.vo.ClubVo; // 导入 ClubVo
import org.lemon.cla.dto.request.ClubSearchRequest;

@Mapper
public interface ClubMapper extends BaseMapper<Club> {

    // 联查用户表的公共字段片段
    String JOIN_USER_SELECT_FIELDS =
            "u.username AS creatorUsername, " +
                    "u.avatar_url AS creatorAvatarUrl, " +
                    "u.real_name AS creatorRealName, " +
                    "u.phone AS creatorPhone, " +
                    "u.email AS creatorEmail, " +
                    "u.role AS creatorRole, " +
                    "u.is_deleted AS creatorIsDeleted "; // <-- 添加 is_deleted 字段

    /**
     * 根据社团ID获取社团详情，包含创建人信息。
     * @param clubId 社团ID
     * @return 社团视图对象
     */
    @Select("SELECT c.*, " +
            JOIN_USER_SELECT_FIELDS + // 复用公共字段
            "FROM club c " +
            "LEFT JOIN user u ON c.creator_id = u.user_id " +
            "WHERE c.club_id = #{clubId}")
    ClubVo selectClubVoById(@Param("clubId") Long clubId);

    /**
     * 分页查询所有社团，包含创建人信息。
     * @param page 分页对象
     * @return 分页社团视图对象列表
     */
    @Select("SELECT c.*, " +
            JOIN_USER_SELECT_FIELDS + // 复用公共字段
            "FROM club c " +
            "LEFT JOIN user u ON c.creator_id = u.user_id " +
            "ORDER BY c.create_time DESC")
    IPage<ClubVo> selectClubVoPage(IPage<ClubVo> page);

    /**
     * 根据多个条件模糊查询社团，包含创建人信息。
     *
     * @param page 分页对象
     * @param req 查询请求DTO
     * @return 分页社团视图对象列表
     */
    @Select("<script>" +
            "SELECT c.*, " +
            JOIN_USER_SELECT_FIELDS + // 复用公共字段
            "FROM club c " +
            "LEFT JOIN user u ON c.creator_id = u.user_id " +
            "<where>" +
            "  <if test='req.clubName != null and req.clubName != \"\"'>" +
            "    AND c.club_name LIKE CONCAT('%', #{req.clubName}, '%')" +
            "  </if>" +
            "  <if test='req.description != null and req.description != \"\"'>" +
            "    AND c.description LIKE CONCAT('%', #{req.description}, '%')" +
            "  </if>" +
            "  <if test='req.creatorId != null'>" +
            "    AND c.creator_id = #{req.creatorId}" +
            "  </if>" +
            "  <if test='req.status != null'>" +
            "    AND c.status = #{req.status}" +
            "  </if>" +
            "</where>" +
            "ORDER BY c.create_time DESC" +
            "</script>")
    IPage<ClubVo> selectClubVoByMultiConditions(
            IPage<ClubVo> page,
            @Param("req") ClubSearchRequest request
    );
}